package shc.graduation.http.task;

import android.text.TextUtils;

import org.litepal.crud.DataSupport;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import shc.graduation.bean.PaperGroup;
import shc.graduation.bean.PaperInfo;
import shc.graduation.utils.log.LogUtils;

/**
 * Created by shuhuiChen on  2016/5/21  18:15.
 * Email ：shuhuiCSH@126.com
 */
public class PaperInfoTask extends BaseTask<PaperInfo> {
    @Override
    void executeTask() {

        if (mBaseGetter == null)
            return;

        boolean isStop = false;  //是否暂停继续抓取网页内容

        // 在这里检查数据库是否已经存在了
        PaperGroup paperGroup = DataSupport.find(PaperGroup.class, mTaskOption.groupIndex);
        if (paperGroup == null) {
            ListenerFail("没有该分组");
            return;
        }

        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        //        String currentDate = "2015-10-04";python
        boolean isFirstSearch = true;
        int repeatRequestCount = 0;

        while (!isStop) {

            if (!isFirstSearch) {
                currentDate = reduceDate(currentDate);
            } else {
                isFirstSearch = false;
            }

            mModelList = DataSupport.where("papergroup_id = ? and paperdate = ?",
                    mTaskOption.groupIndex + "", currentDate).limit(1).find(PaperInfo.class);
            if (mModelList != null && mModelList.size() > 0) {
                isStop = true;
                LogUtils.e("这个日期已经有了：" + currentDate);
                ListenerSuccess("成功");
                LogUtils.e("停止循环");
                mModelList.clear();
                mModelList = null;
                break;
            }

            String url = mTaskOption.websiteUrl + currentDate;// 拼接请求网址链接

            ListenerRunning("正在请求第" + currentDate + "页");
            mModelList = mBaseGetter.getModel(url);

            if (mModelList != null) {
                LogUtils.e("返回对象数量:" + mModelList.size());
            }

            if (mModelList != null && mModelList.size() > 0) {

                repeatRequestCount = 0;

                ListenerRunning("请求的网页内容有东西");

                for (PaperInfo paperInfo : mModelList) {

                    paperInfo.setPapergroup_id(paperGroup.getId());
                    paperInfo.setGroupName(paperGroup.getGroupName());
                    paperInfo.setPaperDate(currentDate);
                    paperInfo.save();

                    ListenerRunning(paperInfo.getAuthor() + "：保存好了");
                    LogUtils.e(paperInfo.getAuthor() + "保存好了");
                }
            } else {
                if (repeatRequestCount >= 30) {
                    isStop = true;
                    ListenerSuccess("成功");
                    LogUtils.e("数据为空，停止循环");
                } else {
                    repeatRequestCount++;
                }
            }
            if (mModelList != null) {
                mModelList.clear();
                mModelList = null;
            }
        }
    }

    /**
     * 让给定的日期减一，例如把 2015-12-18 变成 2015-12-17 返回
     *
     * @param date
     * @return
     */
    private String reduceDate(String date) {

        if (TextUtils.isEmpty(date)) {
            return null;
        }

        String[] dateArrays = date.split("-");
        int year = Integer.valueOf(dateArrays[0]);
        int month = Integer.valueOf(dateArrays[1]);
        int day = Integer.valueOf(dateArrays[2]);

        if (day <= 1) {
            if (month <= 1) {
                year -= 1;
                month = 12;
                day = 31;
            } else {
                month -= 1;
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, month, 0);
                day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                calendar.clear();
            }
        } else {
            day -= 1;
        }

        return year + "-" + new DecimalFormat("00").format(month)
                + "-" + new DecimalFormat("00").format(day);
    }

}
